<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\model;

use think\Db;
use think\Queue;

/**
 * 彩种模型
 */
class LotteryPlay extends ModelBase
{
    protected $insert = ['create_time'];


    /**
     * 连分类表
     */
    public function cate(){
        return $this->belongsTo('LotteryType','cate_id','id');
    }
    /**
     * 连分类表
     */
    public function playcate(){
        return $this->belongsTo('LotteryPlayType','play_cate_id','id');
    }

    public function  getMultAttr($value){

       return $value/2;


    }


    /**
     * 时间自动完成
     */
    public function setCreateTimeAttr()
    {

        return TIME_NOW;
    }
  
//  public function  getCateNameAttr(){
//      $lang=isset($_REQUEST['lang'])?$_REQUEST['lang']:'';
//      return   baidu_translate($this->cate['name'],$lang);
//
//
//    }

//    public function  getDescribeAttr($value){
//
//        $lang=isset($_REQUEST['lang'])?$_REQUEST['lang']:'';
//        return   baidu_translate($value,$lang);
//
//
//    }

//    public function  getContentAttr($value){
//        $lang=isset($_REQUEST['lang'])?$_REQUEST['lang']:'';
//        return   baidu_translate($value,$lang);
//
//    }


    public function new_add_lottery($data){

                // 1.当前任务将由哪个类来负责处理。
                //   当轮到该任务时，系统将生成一个该类的实例，并调用其 fire 方法
                $jobHandlerClassName  = 'app\api\job\Consumer';

                // 2.当前任务归属的队列名称，如果为新队列，会自动创建
                $jobQueueName  	  = "ConsumerJobQueue";


                if (empty($data['univalent']) || $data['univalent'] <= 0) {
                    return ['status'=>1,'msg'=>'单注金额错误'];
                }

                $parameter = explode('|',$data['parameter']);
                if(empty($parameter)){
                    return ['status'=>1,'msg'=>'下注参数错误'];
                }
                $king_id=$user_investment_id=0;
                if(!empty($data['user_investment_id'])){
                    $investment=GamblerKingInvestmentUser::get($data['user_investment_id']);
                    if($investment['state']==5){
                        return ['status'=>1,'msg'=>'由于您本次委托已达自动止赢点，系统已为您强制止赢，请查阅您的业务流水明细'];
                    }

                    if($investment['state']==6){
                        return ['status'=>1,'msg'=>'由于您本次委托已达自动止损点，系统已为您强制止损，请查阅您的业务流水明细'];
                    }
                    $user_investment_id=$data['user_investment_id'];
                    $king_id=$investment['king_id'];
                    $order_count=$investment->order_count;

                }
                if($this->is_old==1){
                    $counts=1;
                }else{
                    $cate_symbol=$this->cate->symbol;
                    include_once(ROOT_PATH.'extend/yzwanfa/'.$cate_symbol.'.php');
                    $_zhushuyzclass = "Lib\\yzwanfa\\{$cate_symbol}";
                    $play_obj= new $_zhushuyzclass();
                    $counts=$play_obj->checkzhushu($this->symbol,$data['parameter']);
                    if(empty($counts)){
                        return ['status'=>1,'msg'=>'下注参数错误'];
                    }

                }

                 $capitals= $data['univalent'] * $counts*$data['mult'];//本金
                if($this->max_consumption>0 && $capitals>$this->max_consumption){
                    return ['status'=>1,'msg'=>lang('最高投注金额为:').$this->max_consumption];
                }
                if($this->min_consumption>0 && $capitals<$this->min_consumption){
                    return ['status'=>1,'msg'=>lang('最低投注金额为:').$this->min_consumption];
                }

                if($this->max_injection>0 && $counts>$this->max_injection){
                    return ['status'=>1,'msg'=>lang('最高投注注数为:').$this->max_injection];
                }
                if($this->total_injection>0 && $counts>$this->total_injection ){
                    return ['status'=>1,'msg'=>lang('已超过最大投注数')];
                }
                $userinfo=Member::get($data['user_id']);
                if(strstr($this->max_reward, '|') && strstr($this->max_reward, '|')){

                    $v1 = explode('|', $this->max_reward);  //最大奖金
                    $v2 = explode('|', $this->max_reward);  //最小奖金
                    $maxjj = "";
                    //echo $userinfo['fandian'];exit;
                    foreach ($v1 as $j => $val) {
                        $maxstr = ((($v1[$j] - $v2[$j]) / getConfig('max_point')) * $userinfo->level['game_return'] + $v2[$j]) . '|';
                        $maxjj .= sprintf("%.2f", filter_money($maxstr, 2)) . '|';
                    }
                    $maxjj = substr($maxjj, 0, -1);
                    $rate = $maxjj;
                }elseif($this->max_reward>0 && $this->min_reward>0){

                    $maxjj = ($this->max_reward - $this->min_reward>0) / getConfig('max_point')* $userinfo->level['game_return'] + $this->min_reward;
                    if (substr(explode('.', $maxjj)[1], 0, 2) == '99') {
                        $maxjj = sprintf("%.2f", ceil($maxjj));
                    } else {
                        $maxjj = sprintf("%.2f", filter_money($maxjj, 2));
                    }
                    $rate = $maxjj;
                }else{
                    $rate=$this->mult/getConfig('max_point')* $userinfo->level['game_return'];
                }

                if ($data['point_odds']) {

                    $rate = $rate -    sprintf("%.2f",round($this->mult) / 100 * $data['point_odds']);

                }

                if($this->id==5 && $counts==5  && $data['mult']%2==0  && $userinfo['just_switch']==1 ){
                    //猜冠军正反码
                    $inverse_codes=['01','02','03','04','05','06','07','08','09','10'];
                    $code=explode(',',$data['parameter']);
                    $res=array_diff($inverse_codes,$code);
                    $inverse_code=implode(',',$res);
                }else{
                    $inverse_code='';
                }
                if(!empty($king_id)){
                    //赌王下注
                    $king=GamblerKing::get($king_id);
                    if($king['king_win_account']<$capitals){
                        return ['status'=>1,'msg'=>'委托可用余额不足'];
                    }

                    $king->king_win_account-=$capitals;
                    $king->save();
                    //写入流水
                    KingAccountLog::create([
                        'user_id'=>$data['user_id'],
                        'king_id'=>$king_id,
                        'number'=>$capitals,
                        'before_blance'=>$king->balance+$capitals,
                        'after_blance'=>$king->balance,
                        'is_add'=>2,
                        'remark'=>'赌王下注'.$data['round'].'期',
                        'type'=>3
                    ]);

                }else{
                    //用户下注
                    $user_account=UserAccount::check(['user_id'=>$data['user_id'],'wallet_id'=>1],false);
                    if($user_account['balance']<$capitals){
                        return ['status'=>1,'msg'=>'总包余额不足'];
                    }
                    $user_account->balance-=$capitals;
                    $user_account->save();
                    //写入流水
                    UserAccountLog::create([
                        'user_id'=>$data['user_id'],
                        'wallet_id'=>1,
                        'before_blance'=>$user_account->balance+$capitals,
                        'after_blance'=>$user_account->balance,
                        'remark'=>'用户下注'.$data['round'].'期',
                        'number'=>$capitals,
                        'type'=>29,
                        'is_add'=>2,
                    ]);
                }
                $dats=$games=[];
                //插入订单
                $dat = array(
                    'user_id'=>$data['user_id'],
                    'lottery_id'=>$data['lottery_id'],
                    'play_id'=>$this->id,
                    'round'=>$data['round'],
                    'number'=>$data['parameter'],
                    'injection_number'=>$counts,
                    'user_investment_id'=>0,
                    'mult'=>$data['mult'],
                    'univalent'=>$data['univalent'],
                    'entrust_count'=>0,
                    'king_id'=>$king_id,
                    'state'=>1,//1待开奖  2中奖 3:未中
                    'money'=>$capitals,   //本金
                    'create_time'=>TIME_NOW,
                    'odds'=>$rate,
                    'point_odds'=>$data['point_odds'],
                    'return_point_money'=>$capitals*$data['point_odds']/100,
                    'is_old'=>$this->is_old,
                    'trade_no'=>'BT'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999),
                    'inverse_code'=>$inverse_code

                );

                //赌王下注
                $game=[
                    'user_id'=>$data['user_id'],
                    'king_id'=>$king_id,
                    'user_investment_id'=>0,
                    'investment_id'=>0,
                    'type'=>4,
                    'entrust_count'=>0,
                    'state'=>3,
                    'order_no'=>$dat['trade_no'],
                    'number'=>$capitals,
                    'create_time'=>TIME_NOW,
                    'users'=>''

                ];
                if(!empty($user_investment_id)){
                    $dat['user_investment_id']=$user_investment_id;

                    $userids=UserKingInvestment::where(['user_investment_id'=>$user_investment_id,'state'=>6])->column('user_id');
                    if($userids){
                        foreach ($userids as $k=>$v){
                            $investment_bet_log=[
                                'create_time'=>TIME_NOW,
                                'user_investment_id'=>$user_investment_id,
                                'user_id'=>$v,
                                'type'=>1,
                                'trade_no'=>$dat['trade_no'],
                                'number'=>$capitals/($order_count+1)
                            ];
                            $investment_bet_logs[]=$investment_bet_log;
                        }
                        $userids=','.implode(',',$userids).',';

                    }else{
                        $investment_bet_logs=[];
                        $userids='';
                    }
                    $investment_bet_log=[
                        'create_time'=>TIME_NOW,
                        'user_investment_id'=>$user_investment_id,
                        'user_id'=>$data['user_id'],
                        'type'=>2,
                        'trade_no'=>$dat['trade_no'],
                        'number'=>$capitals/($order_count+1)
                    ];
                    $investment_bet_logs[]=$investment_bet_log;
                    $dat['entrust_count']=$order_count;
                    $game['entrust_count']=$order_count;
                    $game['user_investment_id']=$user_investment_id;
                    $game['investment_id']=$investment['investment_id'];
                    $game['users']=$userids;

                    if(!empty($investment_bet_logs)){
                        Db::name('investment_bet_log')->insertAll($investment_bet_logs);
                    }


                }
                 $dats[]=$dat;
                 $games[]=$game;


                Db::name('games_log')->insertAll($games);
                Db::name('bets_log')->insertAll($dats);

                //增加业绩
        
                //等级升级
//                $member=Member::get($data['user_id']);
//                $member->is_new=1;
//                $member->lei_money+=$capitals;
//                $member->save();
//                $level_list=UserLevel::where(['status'=>1])->order('id desc')->select();
//                $member->upgrade($capitals,$level_list);
                 if($userinfo['is_banker']==1){
                     Queue::push($jobHandlerClassName,$dat['trade_no'], $jobQueueName);
                 }



                return ['status'=>0,'msg'=>'下注成功'];



    }



    public function subscribe_add_lottery($data){


        if (empty($data['univalent']) || $data['univalent'] <= 0) {
            return ['status'=>1,'msg'=>'单注金额错误'];
        }

        $parameter = explode('|',$data['parameter']);
        if(empty($parameter)){
            return ['status'=>1,'msg'=>'下注参数错误'];
        }

        if($this->is_old==1){
            $counts=1;
        }else{
            $cate_symbol=$this->cate->symbol;
            include_once(ROOT_PATH.'extend/yzwanfa/'.$cate_symbol.'.php');
            $_zhushuyzclass = "Lib\\yzwanfa\\{$cate_symbol}";
            $play_obj= new $_zhushuyzclass();
            $counts=$play_obj->checkzhushu($this->symbol,$data['parameter']);
            if(empty($counts)){
                return ['status'=>1,'msg'=>'下注参数错误'];
            }

        }

        $capitals= $data['univalent'] * $counts*$data['mult'];//本金
        !empty($order_count) &&    $capitals_entrust=$capitals*$order_count;
        $userinfo=Member::get($data['user_id']);
        if(strstr($this->max_reward, '|') && strstr($this->max_reward, '|')){

            $v1 = explode('|', $this->max_reward);  //最大奖金
            $v2 = explode('|', $this->max_reward);  //最小奖金
            $maxjj = "";
            //echo $userinfo['fandian'];exit;
            foreach ($v1 as $j => $val) {
                $maxstr = ((($v1[$j] - $v2[$j]) / getConfig('max_point')) * $userinfo->level['game_return'] + $v2[$j]) . '|';
                $maxjj .= sprintf("%.2f", filter_money($maxstr, 2)) . '|';
            }
            $maxjj = substr($maxjj, 0, -1);
            $rate = $maxjj;
        }elseif($this->max_reward>0 && $this->min_reward>0){

            $maxjj = ($this->max_reward - $this->min_reward>0) / (getConfig('max_point')) * ($userinfo->level['game_return']) + $this->min_reward;
            if (substr(explode('.', $maxjj)[1], 0, 2) == '99') {
                $maxjj = sprintf("%.2f", ceil($maxjj));
            } else {
                $maxjj = sprintf("%.2f", filter_money($maxjj, 2));
            }
            $rate = $maxjj;
        }else{
            $rate=$this->mult/(getConfig('max_point')* $userinfo->level['game_return']);
        }

        if ($data['point_odds']) {

            $rate = $rate -    sprintf("%.2f",round($this->mult) / 100 * $data['point_odds']);

        }
        $rate=format_money($rate,4);
        $lottery_round=LotteryRound::get(['lottery_id'=>$data['lottery_id'],'round'=>$data['round']]);

        //插入订单
        $dat = array(
            'user_id'=>$data['user_id'],
            'lottery_id'=>$data['lottery_id'],
            'play_id'=>$this->id,
            'round'=>$data['round'],
            'number'=>$data['parameter'],
            'injection_number'=>$counts,
            'mult'=>$data['mult'],
            'is_synchro'=>1,
            'univalent'=>$data['univalent'],
            'state'=>1,//1待开奖  2中奖 3:未中
            'money'=>$capitals,   //本金
            'create_time'=>TIME_NOW,
            'start_time'=>$lottery_round->getData('start_time'),
            'end_time'=>$lottery_round->getData('end_time'),
            'point_odds'=>$data['point_odds'],
            'return_point_money'=>$capitals*$data['point_odds']/100,
            'odds'=>$rate,
            'is_old'=>$this->is_old,
            'trade_no'=>'BT'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999),

        );


        if($lottery_round['state']==2){

            $dat['is_synchro']=0;
        }

        Db::name('bets_log_subscribe')->insert($dat);

        if($data['is_synchro']==1){
            //同步下注

            $user_account=UserAccount::check(['user_id'=>$data['user_id'],'wallet_id'=>1],false);
            if($user_account['balance']<$capitals){
                return ['status'=>1,'msg'=>'总包余额不足'];
            }
            $user_account->balance-=$capitals;
            $user_account->save();

            //写入流水
            UserAccountLog::create([
                'user_id'=>$data['user_id'],
                'wallet_id'=>1,
                'before_blance'=>$user_account->balance+$capitals,
                'after_blance'=>$user_account->balance,
                'remark'=>'用户预约下注同步下注'.$data['round'].'期',
                'number'=>$capitals,
                'type'=>29,
                'is_add'=>2,
            ]);

            if($dat['is_synchro']==0){
                if($this->id==5 && $counts==5 && $data['mult']%2==0 && $userinfo['just_switch']==1){
                    //猜冠军正反码
                    $inverse_codes=['01','02','03','04','05','06','07','08','09','10'];
                    $code=explode(',',$data['parameter']);
                    $res=array_diff($inverse_codes,$code);
                    $inverse_code=implode(',',$res);
                }else{
                    $inverse_code='';
                }
                $jobHandlerClassName  = 'app\api\job\Consumer';
                // 2.当前任务归属的队列名称，如果为新队列，会自动创建
                $jobQueueName  	  = "ConsumerJobQueue";
                //当前期数同步下注
                $arr = array(
                    'user_id'=>$data['user_id'],
                    'lottery_id'=>$data['lottery_id'],
                    'play_id'=>$this->id,
                    'round'=>$data['round'],
                    'number'=>$data['parameter'],
                    'injection_number'=>$counts,
                    'user_investment_id'=>0,
                    'mult'=>$data['mult'],
                    'univalent'=>$data['univalent'],
                    'entrust_count'=>0,
                    'state'=>1,//1待开奖  2中奖 3:未中
                    'money'=>$capitals,   //本金
                    'create_time'=>TIME_NOW,
                    'odds'=>$rate,
                    'point_odds'=>$data['point_odds'],
                    'return_point_money'=>$capitals*$data['point_odds']/100,
                    'is_old'=>$this->is_old,
                    'trade_no'=>'BT'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999),
                    'inverse_code'=>$inverse_code
                );
                $game=[
                    'user_id'=>$data['user_id'],
                    'king_id'=>0,
                    'user_investment_id'=>0,
                    'investment_id'=>0,
                    'type'=>4,
                    'entrust_count'=>0,
                    'state'=>3,
                    'order_no'=>$arr['trade_no'],
                    'number'=>$capitals,
                    'create_time'=>TIME_NOW,
                    'users'=>''

                ];

                BetsLog::create($arr);
                GamesLog::create($game);


                if($userinfo['is_banker']==1){
                    Queue::push($jobHandlerClassName,$arr['trade_no'], $jobQueueName);
                }


            }



        }

        return ['status'=>0,'msg'=>'下注成功'];



    }
}
